package com.gxa.pingan.service.impl;

import com.gxa.pingan.common.ExceptionCode;
import com.gxa.pingan.exception.BusinessException;
import com.gxa.pingan.mapper.CityMapper;
import com.gxa.pingan.pojo.City;
import com.gxa.pingan.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.function.IntFunction;

@Service
@Transactional(rollbackFor = Exception.class)
public class CityServiceImpl implements CityService {

    @Resource
    CityMapper cityMapper;

    @Override
    public void add(City city) throws Exception {
        if (city.getCityName()==null){
            throw new BusinessException(ExceptionCode.PARAM_ERROR);
        }
        City byName = cityMapper.findByName(city.getCityName());
        if (byName != null) {
            throw new BusinessException(ExceptionCode.REPEAT_CITY);
        }
        cityMapper.add(city);
    }

    @Override
    public List<City> findAll() throws Exception {
        List<City> allOrByPage = cityMapper.findAll();
        if (allOrByPage.size() > 0) {
            return allOrByPage;
        }
        throw new BusinessException(ExceptionCode.NO_DATA);
    }

    @Override
    public int size() {
        List<City> all = cityMapper.findAll();
        return all.size();
    }

    @Override
    public List<City> findByPage(Integer offset, Integer size) {
        return cityMapper.findByPage((offset - 1) * size, size);
    }

    @Override
    public void deleteCity(Long id) throws Exception {
        City byId = cityMapper.findById(id);
        if (byId != null) {
            cityMapper.deleteCity(id);
            return;
        }
        throw new BusinessException(ExceptionCode.NO_USER);
    }
}
